package com.x.aspect;

import com.x.config.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @title: DynamicDataSourceAspect
 * @Author X
 * @Date: 2021/1/6 17:37
 * @Version 1.0
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    /**
     * 定义切点,
     * 	service包 以及其子包下 第一个参数为String 的方法作为切点
     */
    @Pointcut("@annotation(com.x.common.dynamicdatasource.annotation.DynamicDataSource)")
    public void serviceAspect() {}

    /**
     * 选择数据源
     *
     * @param point
     */
    @Before("serviceAspect()")
    public void switchDataSource(JoinPoint point) {
        Object[] params = point.getArgs();
        String dataSourceId = (String) params[0];
        if(StringUtils.isEmpty(dataSourceId)) return;
        DynamicDataSourceContextHolder.setDataSource(dataSourceId);
        logger.info("Switch DataSource to [{}] in Method [{}]", dataSourceId, point.getSignature());
    }

    /**
     * 重置数据源
     *
     * @param point
     */
    @After("serviceAspect()")
    public void restoreDataSource(JoinPoint point) {
        DynamicDataSourceContextHolder.clearDataSource();
        logger.info("Restore DataSource to [{}] in Method [{}]", DynamicDataSourceContextHolder.getDataSource(), point.getSignature());
    }

}
